import { defineStore } from "pinia";
import { ref, watch } from "vue";

const STORAGE_KEY = 'user_login_info'

export const useUserStore = defineStore('user', () => {
    const isLoggedIn = ref(false);
    const username = ref('');
    const role = ref(''); //'student' or 'teacher'

    // 从Local Storage 中恢复用户状态
    const loadUser = () => {
        const storedData = localStorage.getItem(STORAGE_KEY)
        if (storedData) {
            const userData = JSON.parse(storedData)
            isLoggedIn.value = userData.value
            username.value = userData.value
            role.value = userData.value
        }
    };

    const login = (user) => {
        isLoggedIn.value = true;
        username.value = user.username;
        role.value = user.role;

        localStorage.setItem (
            STORAGE_KEY,
            JSON.stringify({isLoggedIn: true, username: user.username, role: user.role})
        )
    };

    const logout = () => {
        isLoggedIn.value = false;
        username.value = '';
        role.value = '';
        
        localStorage.removeItem(STORAGE_KEY)
    };

    watch (
        [isLoggedIn, username, role],
        () => {
            if (isLoggedIn.value) {
                localStorage.setItem(
                    STORAGE_KEY,
                    JSON.stringify({ isLoggedIn: isLoggedIn.value, username: username.value, role: role.value})
                )
            }
        },
        { deep: true }
    )

    loadUser()
    return {isLoggedIn, username, role, login, logout};
});